package com.yyx.lgb.service.impl;

import com.alibaba.fastjson.JSON;
import com.yyx.lgb.common.exception.LgbException;
import com.yyx.lgb.mapper.UserInfoMapper;
import com.yyx.lgb.model.dto.h5.UserLoginDto;
import com.yyx.lgb.model.dto.h5.UserRegisterDto;
import com.yyx.lgb.model.entity.user.UserInfo;
import com.yyx.lgb.model.vo.common.ResultCodeEnum;
import com.yyx.lgb.model.vo.h5.UserInfoVo;
import com.yyx.lgb.service.UserInfoService;
import com.yyx.lgb.utils.AuthContextUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * ClassName: userInfoServiceImpl
 * Package: com.yyx.lgb.service.impl
 * Description:
 *
 * @Author: yyx
 * @Create: 2025/8/12 - 14:08
 */
@Service
public class UserInfoServiceImpl implements UserInfoService {
    @Autowired
    private UserInfoMapper userInfoMapper;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

        @Transactional(rollbackFor = Exception.class)
        @Override
        public void register(UserRegisterDto userRegisterDto) {

            //1 userRegisterDto获取数据
            String username = userRegisterDto.getUsername();
            String password = userRegisterDto.getPassword();
            String nickName = userRegisterDto.getNickName();
            String code = userRegisterDto.getCode();

            //2 验证码校验
            //2.1 从redis获取发送验证码
            String codeValueRedis = redisTemplate.opsForValue().get("phone:code:" + username);
            //2.2获取输入的验证码，进行比对
            if(!code.equals(codeValueRedis)) {
                throw new LgbException(ResultCodeEnum.VALIDATECODE_ERROR);
            }
            //3校验用户名不能重复
            UserInfo userInfo = userInfoMapper.getByUsername(username);
            if(null != userInfo) {
                throw new LgbException(ResultCodeEnum.USER_NAME_IS_EXISTS);
            }
            //4封装添加数据，调用方法添加数据库
            //保存用户信息
            userInfo = new UserInfo();
            userInfo.setUsername(username);
            userInfo.setNickName(nickName);
            userInfo.setPassword(DigestUtils.md5DigestAsHex(password.getBytes()));
            userInfo.setPhone(username);
            userInfo.setStatus(1);
            userInfo.setSex(0);
            userInfo.setAvatar("http://thirdwx.qlogo.cn/mmopen/vi_32/DYAIOgq83eoj0hHXhgJNOTSOFsS4uZs8x1ConecaVOB8eIl115xmJZcT4oCicvia7wMEufibKtTLqiaJeanU2Lpg3w/132");
            userInfoMapper.save(userInfo);

            //5删除Redis中的数据
            redisTemplate.delete("phone:code:" + username) ;
        }

    //业务接口实现
    @Override
    public String login(UserLoginDto userLoginDto) {
        //1 dto获取用户名和密码
        String username = userLoginDto.getUsername();
        String password = userLoginDto.getPassword();

        //校验参数
        if(StringUtils.isEmpty(username) ||
                StringUtils.isEmpty(password)) {
            throw new LgbException(ResultCodeEnum.DATA_ERROR);
        }
        //2根据用户名查询数据库，得到用户信息
        UserInfo userInfo = userInfoMapper.getByUsername(username);
        if(null == userInfo) {
            throw new LgbException(ResultCodeEnum.LOGIN_ERROR);
        }

        //3 比较密码是否一致
        String md5InputPassword = DigestUtils.md5DigestAsHex(password.getBytes());
        if(!md5InputPassword.equals(userInfo.getPassword())) {
            throw new LgbException(ResultCodeEnum.LOGIN_ERROR);
        }

        //4校验用户是否禁用
        if(userInfo.getStatus() == 0) {
            throw new LgbException(ResultCodeEnum.ACCOUNT_STOP);
        }

        //5生成token
        String token = UUID.randomUUID().toString().replaceAll("-", "");
        //6把用户信息放到redis里面
        redisTemplate.opsForValue().set("user:lgb:" + token, JSON.toJSONString(userInfo), 30, TimeUnit.DAYS);
        //7返回token
        return token;
    }

    @Override
    public UserInfoVo getCurrentUserInfo(String token) {
        UserInfo userInfo = AuthContextUtil.getUserInfo();
        UserInfoVo userInfoVo = new UserInfoVo();
        BeanUtils.copyProperties(userInfo, userInfoVo);
        return userInfoVo ;
    }
}
